<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浙江工商大学食堂点单管理系统 - 管理员界面</title>
    <style>
        body {
            display: flex;
            height: 100vh;
            background-color: #f8f9fa;
        }
        .sidebar {
            width: 250px;
            background-color: #343a40;
            color: white;
            display: flex;
            flex-direction: column;
            padding: 20px;
        }
        .sidebar .logo {
            text-align: center;
            margin-bottom: 20px;
        }
        .sidebar .logo img {
            width: 80%;
        }
        .sidebar nav {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .sidebar nav a {
            color: white;
            text-decoration: none;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
        }
        .sidebar nav a:hover {
            background-color: #495057;
        }
        .content {
            flex-grow: 1;
            padding: 20px;
        }
        .header {
            text-align: center;
            margin-bottom: 20px;
            font-size: 24px;
            font-weight: bold;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: center;
        }
        .btn, .btn-complete, .btn-edit {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            color: white;
            margin-right: 10px;
        }
        .btn {
            background-color: #007bff;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-complete {
            background-color: #28a745;
        }
        .btn-complete:hover {
            background-color: #218838;
        }
        .btn-edit {
            background-color: #ffc107;
            color: black;
        }
        .btn-edit:hover {
            background-color: #e0a800;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .form-group {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column; /* 纵向排列 */
        }

        .form-group label {
            margin-bottom: 5px; /* 给label和输入框之间加点间距 */
        }

        .form-group input, .form-group textarea {
            padding: 8px;
            box-sizing: border-box;
            font-size: 14px;
        }

    </style>
</head>
<body>
    <div class="sidebar">
        <div class="logo">
            <img src="./images/cafeteria-logo.png" alt="Logo">
        </div>
        <nav>
            <a href="javascript:void(0);" onclick="showSection('products')">商品管理</a>
            <a href="javascript:void(0);" onclick="showSection('orders')">订单管理</a>
            <a href="javascript:void(0);" onclick="showSection('windows')">窗口管理</a>
        </nav>
    </div>
    <div class="content">
        <div id="products" class="section">
            <div class="header">商品管理</div>
            <input type="text" id="productSearch" placeholder="搜索商品" oninput="filterProducts()">
            <table id="products-table">
                <thead>
                    <tr>
                        <th>产品ID</th>
                        <th>产品名称</th>
                        <th>价格</th>
                        <th>库存</th>
                        <th>窗口</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 商品数据 -->
                </tbody>
            </table>
            <form id="productForm" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="productName">商品名称</label>
                    <input type="text" id="productName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="productDescription">商品描述</label>
                    <input type="text" id="productDescription" name="description" required>
                </div>
                <div class="form-group">
                    <label for="productPrice">价格</label>
                    <input type="number" id="productPrice" name="price" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="productStock">库存</label>
                    <input type="number" id="productStock" name="stock" required>
                </div>
                <div class="form-group">
                    <label for="windowId">窗口ID</label>
                    <input type="number" id="windowId" name="window_id" required>
                </div>
                <div class="form-group">
                    <label for="productImage">商品图片</label>
                    <input type="file" id="productImage" name="file" required>
                </div>
                
                <button type="submit" class="btn">上传商品</button>
            </form>

            <div class="edit-form" id="editForm" style="display: none;">
                <h3>编辑商品</h3>
                <input type="hidden" id="editProductId">
                <div class="form-group">
                    <label for="editProductName">商品名称:</label>
                    <input type="text" id="editProductName" name="name">
                </div>
                <div class="form-group">
                    <label for="editProductDescription">商品描述:</label>
                    <textarea id="editProductDescription" name="description"></textarea>
                </div>
                <div class="form-group">
                    <label for="editProductPrice">价格:</label>
                    <input type="number" id="editProductPrice" name="price" step="0.01">
                </div>
                <div class="form-group">
                    <label for="editProductStock">库存:</label>
                    <input type="number" id="editProductStock" name="stock">
                </div>
                <div class="form-group">
                    <label for="editWindowId">窗口ID:</label>
                    <input type="number" id="editWindowId" name="window_id">
                </div>
                <button type="button" class="btn" onclick="updateProduct()">更新商品</button>
            </div>
            
        </div>
<!-- 订单列表 -->
        <div id="orders" class="section" style="display:none;">
            <div class="header">订单管理</div>
            <table id="orders-table">
                <thead>
                    <tr>
                        <th>订单号</th>
                        <th>客户ID</th>
                        <th>总价</th>
                        <th>状态</th>
                        <th>订单详情</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="orders-tbody">
                    <!-- 订单数据通过 JavaScript 动态渲染 -->
                </tbody>
            </table>
        </div>


        <div id="windows" class="section" style="display:none;">
        
            <div class="header">窗口管理</div>
            
            <!-- 窗口列表 -->
            <table id="windows-table">
                <thead>
                    <tr>
                        <th>窗口ID</th>
                        <th>窗口名称</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 窗口数据将被插入这里 -->
                </tbody>
            </table>
                    <!-- 新增窗口表单 -->
            <form id="windowForm" method="post">
                <div class="form-group">
                    <label for="windowName">窗口名称</label>
                    <input type="text" id="windowName" name="name" required>
                </div>
                <button type="submit" class="btn">新增窗口</button>
            </form>
            <div class="edit-form" id="editWindowForm" style="display: none;">
                <h3>编辑窗口</h3>
                <input type="hidden" id="editWindowId">
                <div class="form-group">
                    <label for="editWindowName">窗口名称:</label>
                    <input type="text" id="editWindowName" name="name">
                </div>
                <button type="button" class="btn" onclick="updateWindow()">更新窗口</button>
            </div>
    </div>

            <div id="editModal" style="display:none;">
                <!-- 模态框内容 -->
                <form id="editForm">
                    <!-- 表单字段 -->
                    <input type="hidden" id="editProductId" name="id" value="3">
                    <input type="text" id="editProductName" name="name">
                    <input type="text" id="editProductDescription" name="description">
                    <input type="number" id="editProductPrice" name="price" step="0.01">
                    <input type="number" id="editProductStock" name="stock">
                    <input type="number" id="editWindowId" name="window_id">
                    <button type="button" onclick="updateProduct()">更新商品</button>
                </form>
            </div>


    <script>
        function showSection(sectionId) {
            document.querySelectorAll('.section').forEach(section => {
                section.style.display = 'none';
            });
            document.getElementById(sectionId).style.display = 'block';
        }

        document.addEventListener('DOMContentLoaded', function() {
            loadProducts();
            loadOrders();
            loadWindows(); // 加载窗口数据
        });

    // 加载产品的函数
    function loadProducts() {
        fetch('/api/products')
            .then(response => response.json())
            .then(data => {
                const productsTableBody = document.getElementById('products-table').getElementsByTagName('tbody')[0];
                productsTableBody.innerHTML = '';

                data.products.forEach(product => {
                    const row = productsTableBody.insertRow();
                    row.insertCell(0).innerText = product.id;
                    row.insertCell(1).innerText = product.name;
                    row.insertCell(2).innerText = product.price;
                    row.insertCell(3).innerText = product.stock;
                    row.insertCell(4).innerText = product.window_id;

                    const editButton = document.createElement('button');
                    editButton.className = 'btn btn-edit';
                    editButton.textContent = '编辑';
                    editButton.onclick = () => editProduct(product.id);

                    const deleteButton = document.createElement('button');
                    deleteButton.className = 'btn btn-complete';
                    deleteButton.textContent = '删除';
                    deleteButton.onclick = () => deleteProduct(product.id);

                    const actionCell = row.insertCell(5);
                    actionCell.appendChild(editButton);
                    actionCell.appendChild(deleteButton);
                });
            })
            .catch(error => {
                console.error('Failed to load products:', error);
            });
    }

        function filterProducts() {
            const searchQuery = document.getElementById('productSearch').value.toLowerCase();
            const rows = document.getElementById('products-table').getElementsByTagName('tr');
            Array.from(rows).forEach(row => {
                const productName = row.cells[1] ? row.cells[1].textContent.toLowerCase() : '';
                if (productName.includes(searchQuery)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        function completeProduct(productId) {
            fetch(`/api/products/${productId}/complete`, { method: 'PATCH' })
                .then(response => response.json())
                .then(() => loadProducts())
                .catch(error => console.error('完成商品操作失败:', error));
        }


        function deleteProduct(productId) {
            fetch(`/api/products/${productId}`, { method: 'DELETE' })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('商品已删除');
                    loadProducts(); // 重新加载商品列表
                } else {
                    alert('删除商品失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Delete product error:', error);
                alert('删除商品失败');
            });
        }

        // 编辑商品：填充数据到表单
        function editProduct(productId) {
            fetch(`/api/products/${productId}/edit`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 填充表单字段
                    document.getElementById('editProductId').value = data.data.id;
                    document.getElementById('editProductName').value = data.data.name;
                    document.getElementById('editProductDescription').value = data.data.description;
                    document.getElementById('editProductPrice').value = data.data.price;
                    document.getElementById('editProductStock').value = data.data.stock;
                    document.getElementById('editWindowId').value = data.data.window_id;

                    // 显示编辑表单
                    document.getElementById('editForm').style.display = 'block';
                } else {
                    alert('无法加载商品信息');
                }
            })
            .catch(error => console.error('Error:', error));
        }

        // 更新商品：提交数据
        function updateProduct() {
            const productId = document.getElementById('editProductId').value;
            const updatedData = {
                name: document.getElementById('editProductName').value,
                description: document.getElementById('editProductDescription').value,
                price: parseFloat(document.getElementById('editProductPrice').value),
                stock: parseInt(document.getElementById('editProductStock').value),
                window_id: document.getElementById('editWindowId').value
            };

            fetch(`/api/products/${productId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('商品更新成功');
                    loadProducts(); // 重新加载商品列表
                    document.getElementById('editForm').style.display = 'none'; // 隐藏编辑表单
                } else {
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => console.error('Error:', error));
        }

        function loadOrders() {
            fetch('/api/orders')
                .then(response => response.json())
                .then(data => {
                    const ordersTableBody = document.getElementById('orders-table').getElementsByTagName('tbody')[0];
                    ordersTableBody.innerHTML = '';
                    data.forEach(order => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${order.id}</td>
                            <td>${order.customerId}</td>
                            <td>${order.customerAddress}</td>
                            <td>${order.products.map(p => `${p.name} (${p.quantity})`).join(', ')}</td>
                            <td>${order.totalPrice}</td>
                            <td>${order.status}</td>
                            <td><button class="btn-complete">发货</button></td>
                        `;
                        ordersTableBody.appendChild(row);
                    });
                })
                .catch(error => console.error('加载订单数据失败:', error));
        }

        document.getElementById('windowForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const windowName = document.getElementById('windowName').value;

            fetch('/api/windows', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: windowName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('窗口已添加');
                    loadWindows(); // 重新加载窗口列表
                    document.getElementById('windowForm').reset(); // 清空表单
                } else {
                    alert('添加窗口失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加窗口失败');
            });
        });

        function loadWindows() {
            fetch('/api/windows')
            .then(response => response.json())
            .then(data => {
                const windowsTableBody = document.getElementById('windows-table').getElementsByTagName('tbody')[0];
                windowsTableBody.innerHTML = ''; // 清空表格
                data.windows.forEach(window => {
                    const row = windowsTableBody.insertRow();
                    row.insertCell(0).innerText = window.id;
                    row.insertCell(1).innerText = window.name;
                    // 添加操作列，如果需要的话
                                // 创建操作列的单元格
                    const actionCell = row.insertCell(2);
                    const editButton = document.createElement('button');
                    editButton.className = 'btn btn-edit';
                    editButton.textContent = '编辑';
                    editButton.onclick = () => editWindow(window.id);
                    actionCell.appendChild(editButton);

                    const deleteButton = document.createElement('button');
                    deleteButton.className = 'btn btn-complete';
                    deleteButton.textContent = '删除';
                    deleteButton.onclick = () => deleteWindow(window.id);
                    actionCell.appendChild(deleteButton);
                });
            })
            .catch(error => console.error('加载窗口数据失败:', error));
        }

    // 页面加载完成后自动调用
    document.addEventListener('DOMContentLoaded', function() {
        loadWindows(); // 页面加载完成后加载窗口数据
    });

            function editWindow(windowId) {
            fetch(`/api/windows/${windowId}/edit`)  // 假设您有一个用于获取窗口详情的API
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('editWindowId').value = data.id;
                    document.getElementById('editWindowName').value = data.name;
                    document.getElementById('editWindowForm').style.display = 'block';
                } else {
                    alert('Failed to fetch window: ' + data.message);
                }
            })
            .catch(error => console.error('Edit window error:', error));
        }

        function deleteWindow(windowId) {
            fetch(`/api/windows/${windowId}`, { method: 'DELETE' })
            .then(response => {
                if (response.ok) {
                    alert('窗口已删除');
                    loadWindows(); // 重新加载窗口列表
                } else {
                    alert('删除窗口失败，该窗口有餐品');
                }
            })
            .catch(error => console.error('Delete window error:', error));
        }
        function updateWindow() {
            const windowId = document.getElementById('editWindowId').value;
            const updatedData = {
                name: document.getElementById('editWindowName').value
            };
            
            fetch(`/api/windows/${windowId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedData)
            })
            .then(response => response.json())
            .then(() => {
                loadWindows();
                document.getElementById('editWindowForm').style.display = 'none';
            })
            .catch(error => console.error('更新窗口数据失败:', error));
        }

        document.getElementById('productForm').addEventListener('submit', function(event) {
            event.preventDefault();
            let formData = new FormData(this);

            fetch('/api/products', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('商品已添加/更新');
                    loadProducts();
                } else {
                    alert('添加商品失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加商品失败');
            });
        });


        
        // 获取订单列表
        function loadOrders() {
            fetch('/api/admin/orders')
                .then(response => response.json())
                .then(data => {
                    const ordersTableBody = document.getElementById('orders-tbody');
                    ordersTableBody.innerHTML = ''; // 清空现有的表格数据

                    data.orders.forEach(order => {
                        const row = ordersTableBody.insertRow();
                        row.insertCell(0).innerText = order.id;
                        row.insertCell(1).innerText = order.consumer_id;
                        row.insertCell(2).innerText = order.total_price;

                        // 处理订单状态显示
                        const statusCell = row.insertCell(3);
                        const statusText = order.status === 'pending' ? '未完成' : (order.status === 'completed' ? '完成' : '已取消');
                        statusCell.innerText = statusText;

                        // 新增列：显示订单详情（菜品信息）
                        const itemsCell = row.insertCell(4);
                        let itemsText = '';
                        order.items.forEach(item => {
                            itemsText += `菜品名称: ${item.product_name}, 数量: ${item.quantity}, 单价: ${item.price}元\n`;
                        });
                        itemsCell.innerText = itemsText;

                        // 操作列：更新订单状态
                        const actionCell = row.insertCell(5);
                        const completeButton = document.createElement('button');
                        completeButton.className = 'btn btn-complete';
                        completeButton.textContent = '出餐';
                        completeButton.onclick = () => completeOrder(order.id);
                        actionCell.appendChild(completeButton);
                    });
                })
                .catch(error => {
                    console.error('Failed to fetch orders:', error);
                    alert('加载订单失败，请稍后重试。');
                });
        }


        // 发送订单ID到后端
        function completeOrder(orderId) {
            fetch(`/api/admin/orders/${orderId}/complete`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ order_id: orderId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('订单已完成，库存已更新。');
                    loadOrders(); // 重新加载订单列表
                } else {
                    alert('完成失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error completing order:', error);
                alert('完成失败，请稍后重试。');
            });
        }

    </script>
</body>
</html>
